<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\ManagerInterface;
use App\User;
use Laracasts\Flash\Flash;
class ManagerServiceRepository implements ManagerInterface{

    public function allUser($perPage){
        return User::orderBy('id','desc')->paginate($perPage);
    }
    public function searchKeyWords($data,$perPage){
        return User::where('name','like','%'.$data['keywords'].'%')->orWhere('username','like','%'.$data['keywords'].'%')->paginate($perPage);
    }
    public function create(array $data){
        $data = User::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'email'  => $data['email'],
            'password'  => bcrypt($data['password']),
        ]);
        if( $data == 'true' ){
            Flash('管理员添加成功','success');
        }else{
//            Flash('管理员添加失败','errors');
            Flash('管理员添加失败','warning');
        }
        return $data;
    }

    public function findById($id){
        return User::find($id);
    }
    public function update(array $data, $id){
        if( empty($data['password']) ){
            $date =  User::where(['id'=>$id])->update([
                'name' => $data['name'],
                'username' => $data['username'],
                'email'  => $data['email'],
            ]);
        }else{
            $date =  User::where(['id'=>$id])->update([
                'name' => $data['name'],
                'username' => $data['username'],
                'email'  => $data['email'],
                'password'  => bcrypt($data['password']),
            ]);
        }
        if( $date ){
            Flash('管理员更新成功!','success');
//            Flash::success('管理员更新成功!');
        }else{
            Flash('管理员更新失败！','error');
//            Flash::error('管理员更新失败！');
        }
        return $data;

    }
    public function delete($id){
        $data = User::destroy($id);
        if( $data == true ){
            $data = [
                'status' => 1,
                'msg'   => '删除成功！',
            ];
        }else{
            $data = [
                'status' => 0,
                'msg'   => '删除失败！',
            ];
        }
        return response()->json($data);
    }
}